﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using SmoLiteApi.Exceptions;

namespace SmoLiteApi.Helper
{
    /// <summary/>
    internal class SqlCommandHelper : IDisposable
    {
        private SqlCommand _sqlCommand;

        /// <summary/>
        private SqlCommandHelper(SqlCommand sqlCommand)
        {
            this._sqlCommand = sqlCommand;
        }

        /// <summary/>
        internal static SqlCommandHelper FetchSqlCommand(
            SqlConnection sqlConnection,
            string sql)
        {
            SqlCommand sqlCommand = sqlConnection.CreateCommand();

            // set attributes
            sqlCommand.CommandText = sql;
            sqlCommand.CommandType = CommandType.Text;

            return new SqlCommandHelper(sqlCommand);
        }

        /// <summary/>
        internal static SqlCommandHelper FetchProcedureCommand(
            SqlConnection sqlConnection,
            string procedure)
        {
            SqlCommand sqlCommand = sqlConnection.CreateCommand();

            // set attributes
            sqlCommand.CommandText = procedure;
            sqlCommand.CommandType = CommandType.StoredProcedure;

            return new SqlCommandHelper(sqlCommand);
        }

        /// <summary/>
        internal SqlParameterCollection Parameters
        {
            get { return this._sqlCommand.Parameters; }
        }

        /// <summary/>
        internal int CommandTimeout
        {
            set { this._sqlCommand.CommandTimeout = value; }
        }

        /// <summary/>
        internal void ExecuteNonQuery()
        {
            try
            {
                this._sqlCommand.ExecuteNonQuery();
            }
            catch (SqlException sqlException)
            {
                throw new SmoException(this._sqlCommand.CommandText, sqlException);
            }
        }

        /// <summary/>
        internal SqlDataReader ExecuteReader()
        {
            return this._sqlCommand.ExecuteReader();
        }

        /// <summary/>
        public void Dispose()
        {
            this._sqlCommand.Dispose();
        }
    }
}
